<template>
  <div v-loading="detailInfoShow">
    <div class="requestAdd" v-if="!selectionMaterialShow && !requestDetailShow">
      <!-- 筛选按钮 -->
      <div class="search-button" v-if="!contactAddShow">
        <el-button
          v-if="pageType === 'check' && route.name === 'InquiryCheck'"
          class="btn save"
          @click="handleCheckBtn2(projectFormRef, 3, '同意')"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >同意</el-button
        >
        <el-button
          v-if="pageType === 'check' && route.name === 'InquiryCheck'"
          class="btn withdraw"
          @click="handleCheckBtn2(projectFormRef, 4, '拒绝')"
          ><el-icon class="icon" color="#fff"> <DocumentDelete /> </el-icon
          >拒绝</el-button
        >

        <el-button
          v-if="pageType === 'check' && route.name === 'InquiryCheck'"
          class="btn withdraw"
          @click="handleCheckBtn2(projectFormRef, 6, '驳回')"
          ><el-icon class="icon" color="#fff"> <DocumentDelete /> </el-icon
          >驳回</el-button
        >
        <el-button
          v-if="pageType !== 'detail' && pageType !== 'check'"
          class="btn submit"
          @click="handleAddSave(requestFormRef, 1)"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >提交</el-button
        >
        <el-button
          v-if="pageType !== 'detail' && pageType !== 'check'"
          class="btn save"
          @click="handleAddSave(requestFormRef, 0)"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >存为草稿</el-button
        >
        <el-button class="btn direction" @click="handleBack"
          ><el-icon class="icon" color="#fff"> <Back /> </el-icon
          >返回</el-button
        >
      </div>
      <el-collapse v-model="activeNames">
        <!-- 基础信息 -->
        <el-collapse-item
          name="1"
          v-if="!contactAddShow"
          class="transform-down"
        >
          <template #title>
            <span class="circle"></span>
            <span class="collapse-title"
              >{{
                pageType !== "detail" && pageType !== "check "
                  ? pageType === "add"
                    ? ""
                    : "编辑"
                  : ""
              }}基础信息</span
            >
          </template>
          <div class="request-info">
            <el-form
              :model="requestForm"
              ref="requestFormRef"
              :rules="queryRules"
              label-width="100px"
              v-enterToNext
              :disabled="pageType === 'detail' || pageType === 'check'"
            >
              <el-row>
                <el-col :span="6">
                  <el-form-item label="询比价编号：">
                    <el-input
                      disabled
                      v-model="requestForm.inquiryCode"
                      placeholder="自动获取"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item
                    label="申请日期："
                    prop="applicantDate"
                    label-width="135"
                  >
                    <el-date-picker
                      v-model="requestForm.applicantDate"
                      format="YYYY/MM/DD"
                      class="search-input"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="请选择"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item
                    label="申请人："
                    prop="applicantId"
                    label-width="135"
                  >
                    <el-select
                      filterable
                      v-model="requestForm.applicantId"
                      placeholder="请选择"
                      clearable
                      class="search-input"
                      @change="handleUserChange"
                      value-key="userId"
                      placement="bottom-end"
                    >
                      <!-- <el-option
                        v-for="dict in userList"
                        :key="dict.userId"
                        :label="dict.nickName"
                        :value="dict.userId"
                      /> -->
                      <el-option disabled :value="null">
                        <div class="auto-top">
                          <span class="auto-item">人员姓名</span>
                          <span class="auto-item">联系方式</span>
                          <span class="auto-item">职位</span>
                          <span class="auto-item">部门</span>
                        </div>
                      </el-option>
                      <el-option
                        v-for="dict in userList"
                        :key="dict.userId"
                        :value="dict.userId"
                        :label="dict.nickName"
                      >
                        <div style="display: flex">
                          <div class="auto-item" :title="dict.nickName">
                            {{ dict.nickName }}
                          </div>
                          <div class="auto-item" :title="dict.phonenumber">
                            {{ dict.phonenumber ? dict.phonenumber : "--" }}
                          </div>
                          <div class="auto-item" :title="dict.postName">
                            {{ dict.postName ? dict.postName : "--" }}
                          </div>
                          <div class="auto-item" :title="dict.fullDeptName">
                            {{ dict.fullDeptName ? dict.fullDeptName : "--" }}
                          </div>
                        </div>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="申请部门：" label-width="135">
                    <el-input
                      disabled
                      v-model="requestForm.deptName"
                      placeholder="自动获取"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="采购说明：" prop="remarks">
                    <el-input
                      style="width: 100%"
                      v-model="requestForm.remarks"
                      type="textarea"
                      placeholder="请输入"
                      maxlength="2000"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
        <!-- 询比价信息列表 -->
        <el-collapse-item
          name="2"
          style="position: relative"
          v-if="!contactAddShow"
        >
          <!-- class="transform-down" -->
          <template #title>
            <span class="circle"></span>
            <span class="collapse-title">关联请购单</span>
            <div
              class="nofixed-search-button button-position"
              v-if="pageType !== 'detail' && pageType !== 'check'"
            >
              <el-button
                class="btn submit"
                @click.stop="handleRequestChoose"
                style="width: 150px"
                ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
                >选择关联请购单</el-button
              >
            </div>
          </template>
          <div class="contact-info">
            <!-- 表格数据 -->
            <el-table
              :data="
                pageType !== 'detail' && pageType !== 'check'
                  ? RequestChooseList
                  : requestListSplit
              "
              border
              :height="'100%'"
              :header-cell-style="{ 'text-align': 'center' }"
              style="margin-bottom: 20px"
              :row-class-name="tableRowClassName"
            >
              <!-- 操作模式 -->
              <el-table-column
                label="操作"
                align="center"
                :show-overflow-tooltip="true"
                width="60px"
                v-if="pageType !== 'detail' && pageType !== 'check'"
              >
                <template #default="{ row, $index }">
                  <div class="table-operate">
                    <img
                      src="@/assets/icons/images/delete.png"
                      class="table-icon"
                      title="删除"
                      @click="handleRequestOperate('delete', row, $index)"
                    />
                  </div> </template
              ></el-table-column>
              <el-table-column
                v-if="pageType === 'detail' || pageType === 'check'"
                width="60"
                label="序号"
                align="center"
              >
                <template #default="{ row, $index }">
                  {{ row.index }}.{{ row.childrenIndex }}
                </template>
              </el-table-column>
              <el-table-column
                label="请购编号"
                prop="purchaseApplyCode"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="物料编号"
                prop="materialCode"
                :show-overflow-tooltip="true"
                min-width="160"
              >
                <template #default="{ row }">
                  <span>{{ row.materialCode ? row.materialCode : "--" }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="物料名称"
                prop="materialName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="出厂型号"
                prop="factoryCode"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="技术参数"
                prop="technologyParameter"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="单位"
                prop="materialUnitName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="请购数量"
                prop="purchaseNumber"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="单价（元）"
                prop="purchasePrice"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="总价（元）"
                :show-overflow-tooltip="true"
                min-width="160"
              >
                <template #default="{ row }">
                  {{ row.purchasePrice * row.purchaseNumber }}
                </template>
              </el-table-column>
              <el-table-column
                label="到货周期"
                prop="deliveryCycle"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="物料图片"
                :show-overflow-tooltip="true"
                min-width="200"
              >
                <template #default="{ row }">
                  <div class="image-content" v-if="row.suppFileInfoVos">
                    <!-- <template > -->
                    <el-image
                      v-for="(item, index) in row.suppFileInfoVos"
                      :key="index"
                      :preview-teleported="true"
                      style="width: 30px; height: 30px; margin-right: 5px"
                      :src="item.url"
                      :preview-src-list="showImg(item.url)"
                    >
                      <template #error>
                        <div class="image-slot">
                          <el-icon><icon-picture /></el-icon>
                        </div>
                      </template>
                    </el-image>
                    <!-- </template> -->
                  </div>
                  <span v-if="!row.suppFileInfoVos"> 暂无图片 </span>
                </template>
              </el-table-column>
              <el-table-column
                label="参考链接"
                prop="referenceLink"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="供应商"
                prop="supplierName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="生产厂商"
                prop="manufactureName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
            </el-table>
          </div>
        </el-collapse-item>
        <!-- 添加询比价信息 -->
        <el-collapse-item
          name="3"
          style="position: relative"
          v-if="contactAddShow"
          class="transform-up"
        >
          <template #title>
            <span class="circle"></span>
            <span class="collapse-title">添加询比价</span>
            <div class="nofixed-search-button button-position">
              <el-button class="btn save" @click.stop="handleHand"
                ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
                >手动添加</el-button
              >
              <el-button class="btn submit" @click.stop="handleMaterial"
                ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
                >选择物料</el-button
              >
            </div>
          </template>
          <div class="request-info">
            <el-form
              :model="contactForm"
              ref="contactFormRef"
              label-width="100px"
              :rules="queryContactRules"
              v-enterToNext
            >
              <!--  -->
              <el-row>
                <el-col :span="6">
                  <el-form-item label="物料编号：">
                    <el-input
                      v-model="contactForm.materialCode"
                      placeholder="自动生成"
                      clearable
                      class="search-input"
                      disabled=""
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="物料名称：" prop="materialName">
                    <el-input
                      :disabled="contactForm.materialCode !== ''"
                      ref="refInput"
                      v-model="contactForm.materialName"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="出厂型号：" prop="factoryCode">
                    <el-input
                      :disabled="contactForm.materialCode !== ''"
                      v-model="contactForm.factoryCode"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="技术参数：" prop="technologyParameter">
                    <el-input
                      :disabled="contactForm.materialCode !== ''"
                      v-model="contactForm.technologyParameter"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="0">
                <el-col :span="6">
                  <el-form-item label="单位：" prop="materialUnit">
                    <el-select
                      :disabled="contactForm.materialCode !== ''"
                      v-model="contactForm.materialUnit"
                      placeholder="请选择"
                      clearable
                      class="search-input"
                      @change="handleUnitChange"
                    >
                      <el-option
                        v-for="dict in unitList"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="采购数量：" prop="purchaseNumber">
                    <el-input
                      type="Number"
                      v-model="contactForm.purchaseNumber"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                      @blur="handlePrice"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="预算单价：" prop="budgetedPrice">
                    <el-input
                      type="Number"
                      v-model="contactForm.budgetedPrice"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                      @blur="handlePrice"
                    >
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="预算总价：">
                    <el-input
                      disabled
                      v-model="contactForm.budgeteAllPrice"
                      placeholder="自动获取"
                      clearable
                      class="search-input"
                    >
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6">
                  <el-form-item label="询价单价：" prop="purchasePrice">
                    <el-input
                      type="Number"
                      v-model="contactForm.purchasePrice"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                      @blur="handlePrice"
                    >
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="税率：" prop="taxRate">
                    <!-- <el-input
                      type="Number"
                      v-model="contactForm.taxRate"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                      @blur="handlePrice"
                    >
                      <template #append>%</template>
                    </el-input> -->
                    <el-select
                      v-model="contactForm.taxRate"
                      placeholder="请选择"
                      clearable
                      class="search-input"
                      @change="handlePrice"
                    >
                      <el-option
                        v-for="dict in taxRateList"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="税额：">
                    <el-input
                      pattern="/^\d+(\.\d{1,2})?$/"
                      disabled
                      type="Number"
                      v-model="contactForm.taxAmount"
                      placeholder="单价、自动计算"
                      clearable
                      class="search-input"
                      @blur="handlePrice"
                    >
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="不含税金额：">
                    <el-input
                      disabled
                      type="Number"
                      v-model="contactForm.noTaxAmount"
                      placeholder="单价、自动计算"
                      clearable
                      class="search-input"
                      @blur="handlePrice"
                    >
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="总金额：">
                    <el-input
                      disabled
                      v-model="contactForm.allPrice"
                      placeholder="自动获取"
                      clearable
                      class="search-input"
                    >
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="运费：" prop="freight">
                    <el-input
                      type="Number"
                      v-model="contactForm.freight"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                      @blur="handlePrice"
                    >
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="发票类型：" prop="invoiceType">
                    <el-select
                      v-model="contactForm.invoiceType"
                      placeholder="请选择"
                      clearable
                      class="search-input"
                      @change="handleTypeChange"
                    >
                      <el-option
                        v-for="dict in typeList"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <!-- </el-row>
              <el-row> -->
                <el-col :span="6">
                  <el-form-item label="到货周期：" prop="deliveryCycle">
                    <el-input
                      v-model="contactForm.deliveryCycle"
                      placeholder="如：一周内。方便采购了解优先级，以保障供应时效"
                      clearable
                      class="search-input"
                      :maxlength="20"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="渠道：" prop="channel">
                    <el-select
                      v-model="contactForm.channel"
                      placeholder="请选择"
                      clearable
                      class="search-input"
                      @change="handleChannelChange"
                    >
                      <el-option
                        v-for="dict in channelList"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="供应商：">
                    <!-- <el-autocomplete
                      :disabled="contactForm.materialCode !== ''"
                      popper-class="autoclass"
                      v-model="contactForm.supplierName"
                      :fetch-suggestions="querySearch"
                      placeholder="请输入"
                      @select="handleSuppliereSelect"
                      style="width: 268px"
                      clearable
                      placement="bottom-end"
                    >
                      <template #default="{ item }">
                        <div class="auto-top" style="display: flex">
                          <div class="auto-item">供应商编号</div>
                          <div class="auto-item">供应商简称</div>
                          <div class="auto-item">供应商全称</div>
                          <div class="auto-item">供应商地址</div>
                        </div>
                        <div style="display: flex; width: 500px">
                          <div class="auto-item" :title="item.supplierCode">
                            {{ item.supplierCode }}
                          </div>
                          <div
                            class="auto-item"
                            :title="item.supplierAbbreviation"
                          >
                            {{ item.supplierAbbreviation }}
                          </div>
                          <div class="auto-item" :title="item.supplierName">
                            {{ item.supplierName }}
                          </div>
                          <div
                            class="auto-item"
                            :title="`${item.provinceName}${item.cityName}${item.areaName}`"
                          >
                            {{ item.provinceName }}{{ item.cityName
                            }}{{ item.areaName }}
                          </div>
                        </div>
                      </template>
                    </el-autocomplete> -->
                    <el-select
                      filterable
                      v-model="contactForm.supplierId"
                      placeholder="请选择"
                      clearable
                      class="search-input"
                      :disabled="contactForm.materialCode !== ''"
                    >
                      <template v-if="suppliereList.length">
                        <el-option disabled :value="{}">
                          <div class="auto-top">
                            <span class="auto-item">供应商编号</span>
                            <span class="auto-item">供应商简称</span>
                            <span class="auto-item">供应商全称</span>
                            <span class="auto-item">供应商地址</span>
                          </div>
                        </el-option>
                        <el-option
                          v-for="dict in suppliereList"
                          :key="dict.supplierId"
                          :value="dict.supplierId"
                          :label="dict.supplierName"
                        >
                          <div style="display: flex">
                            <div class="auto-item" :title="dict.supplierCode">
                              {{ dict.supplierCode }}
                            </div>
                            <div
                              class="auto-item"
                              :title="dict.supplierAbbreviation"
                            >
                              {{ dict.supplierAbbreviation }}
                            </div>
                            <div class="auto-item" :title="dict.supplierName">
                              {{ dict.supplierName }}
                            </div>
                            <div
                              class="auto-item"
                              :title="
                                dict.provinceName
                                  ? `${dict.provinceName}${dict.cityName}${dict.areaName}`
                                  : ''
                              "
                            >
                              {{ dict.provinceName }}{{ dict.cityName
                              }}{{ dict.areaName }}
                            </div>
                          </div>
                        </el-option>
                      </template>

                      <template v-else>
                        <el-option
                          v-for="dict in []"
                          :key="dict.supplierId"
                          :label="dict.supplierId"
                          :value="dict.supplierId"
                        />
                      </template>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="生产厂商：">
                    <!-- <el-autocomplete
                      :disabled="contactForm.materialCode !== ''"
                      popper-class="autoclass"
                      v-model="contactForm.manufactureName"
                      :fetch-suggestions="querySearch"
                      placeholder="请输入"
                      @select="handleSuppliereSelect"
                      style="width: 268px"
                      clearable
                      placement="bottom-end"
                    >
                      <template #default="{ item }">
                        <div class="auto-top" style="display: flex">
                          <div class="auto-item">供应商编号</div>
                          <div class="auto-item">供应商简称</div>
                          <div class="auto-item">供应商全称</div>
                          <div class="auto-item">供应商地址</div>
                        </div>
                        <div style="display: flex; width: 500px">
                          <div class="auto-item" :title="item.supplierCode">
                            {{ item.supplierCode }}
                          </div>
                          <div
                            class="auto-item"
                            :title="item.supplierAbbreviation"
                          >
                            {{ item.supplierAbbreviation }}
                          </div>
                          <div class="auto-item" :title="item.supplierName">
                            {{ item.supplierName }}
                          </div>
                          <div
                            class="auto-item"
                            :title="`${item.provinceName}${item.cityName}${item.areaName}`"
                          >
                            {{ item.provinceName }}{{ item.cityName
                            }}{{ item.areaName }}
                          </div>
                        </div>
                      </template>
                    </el-autocomplete> -->
                    <el-select
                      filterable
                      v-model="contactForm.manufacturerId"
                      placeholder="请选择"
                      clearable
                      class="search-input"
                      :disabled="contactForm.materialCode !== ''"
                    >
                      <template v-if="suppliereList.length">
                        <el-option disabled :value="{}">
                          <div class="auto-top">
                            <span class="auto-item">供应商编号</span>
                            <span class="auto-item">供应商简称</span>
                            <span class="auto-item">供应商全称</span>
                            <span class="auto-item">供应商地址</span>
                          </div>
                        </el-option>
                        <el-option
                          v-for="dict in suppliereList"
                          :key="dict.supplierId"
                          :value="dict.supplierId"
                          :label="dict.supplierName"
                        >
                          <div style="display: flex">
                            <div class="auto-item" :title="dict.supplierCode">
                              {{ dict.supplierCode }}
                            </div>
                            <div
                              class="auto-item"
                              :title="dict.supplierAbbreviation"
                            >
                              {{ dict.supplierAbbreviation }}
                            </div>
                            <div class="auto-item" :title="dict.supplierName">
                              {{ dict.supplierName }}
                            </div>
                            <div
                              class="auto-item"
                              :title="
                                dict.provinceName
                                  ? `${dict.provinceName}${dict.cityName}${dict.areaName}`
                                  : ''
                              "
                            >
                              {{ dict.provinceName }}{{ dict.cityName
                              }}{{ dict.areaName }}
                            </div>
                          </div>
                        </el-option>
                      </template>

                      <template v-else>
                        <el-option
                          v-for="dict in []"
                          :key="dict.supplierId"
                          :label="dict.supplierId"
                          :value="dict.supplierId"
                        />
                      </template>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
        <!-- 询比价信息列表 -->
        <el-collapse-item
          name="4"
          style="position: relative"
          v-if="!contactAddShow"
        >
          <!-- class="transform-down" -->
          <template #title>
            <span class="circle"></span>
            <span class="collapse-title">询比价信息明细</span>
            <div
              v-if="
                pageType !== 'detail' && pageType !== 'check' && !contactAddShow
              "
              class="nofixed-search-button button-position"
            >
              <el-button class="btn add" @click.stop="handleContactOperate"
                ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
                >添加</el-button
              >
            </div>
          </template>
          <div class="contact-info">
            <!-- 表格数据 -->
            <el-table
              row-key="batchNumber"
              :default-expand-all="true"
              :data="purchaseDetailTable"
              border
              :height="
                pageType === 'detail' || pageType === 'check'
                  ? '100%'
                  : contactAddShow
                  ? '320px'
                  : '280px'
              "
              :header-cell-style="{ 'text-align': 'center' }"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
              show-summary
              sum-text="合计"
              :summary-method="getSummaries"
            >
              <el-table-column type="" width="1" align="center" />
              <!-- 操作模式 -->
              <el-table-column
                type=""
                label="操作"
                align="center"
                :show-overflow-tooltip="true"
                width="100px"
                v-if="pageType !== 'detail' && pageType !== 'check'"
              >
                <template #default="{ row, $index }">
                  <div class="table-operate" v-if="!row.parentId">
                    <img
                      src="@/assets/icons/images/edit.png"
                      class="table-icon"
                      title="编辑"
                      @click="handleTreeOperate('edit', row, $index)"
                    />
                    <img
                      src="@/assets/icons/images/delete.png"
                      class="table-icon"
                      title="删除"
                      @click="handleTreeOperate('delete', row, $index)"
                    />
                  </div> </template
              ></el-table-column>
              <!-- <el-table-column
          type="index"
          label="序号"
          width="70"
          align="center"
        /> -->
              <el-table-column
                v-if="pageType !== 'add' && pageType !== 'edit'"
                type="index"
                width="60"
                label="序号"
                align="center"
              >
                <template #default="{ row, $index }">
                  <div v-if="!row.parentId">{{ indexList[$index] }}</div>
                  <div v-else>{{ null }}</div>
                </template>
              </el-table-column>
              <el-table-column
                type=""
                label="物料编号"
                prop="materialCode"
                :show-overflow-tooltip="true"
                min-width="160"
              >
                <template #default="{ row }">
                  <span>{{ row.materialCode ? row.materialCode : "--" }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="物料名称"
                prop="materialName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="出厂型号"
                prop="factoryCode"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="技术参数"
                prop="technologyParameter"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="单位"
                prop="materialUnitName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="采购数量"
                prop="purchaseNumber"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="预算单价（元）"
                prop="budgetedPrice"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="预算总价（元）"
                :show-overflow-tooltip="true"
                min-width="160"
                prop="budgeteAllPrice"
              >
                <!-- <template #default="{ row }">
                  {{ row.budgetedPrice * row.purchaseNumber }}
                </template> -->
              </el-table-column>
              <el-table-column
                label="询价单价（元）"
                prop="purchasePrice"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="税率（%）"
                prop="taxRate"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="税额（元）"
                prop="taxAmount"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="不含税金额（元）"
                prop="noTaxAmount"
                :show-overflow-tooltip="true"
                min-width="160"
              />

              <el-table-column
                label="运费（元）"
                prop="freight"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="总金额（元）"
                :show-overflow-tooltip="true"
                min-width="160"
                prop="allPrice"
              >
                <!-- <template #default="{ row }">
                  {{ row.purchasePrice * row.purchaseNumber + row.freight }}
                </template> -->
              </el-table-column>
              <el-table-column
                label="发票类型"
                prop="invoiceTypeName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="到货周期"
                prop="deliveryCycle"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="渠道"
                prop="channelName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="供应商"
                prop="supplierName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="生产厂商"
                prop="manufactureName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
            </el-table>
          </div>
        </el-collapse-item>
        <el-collapse-item name="5" style="position: relative" v-else>
          <!-- class="transform-down" -->
          <template #title>
            <span class="circle"></span>
            <div class="collapse-title">
              <div
                class="collapse-title-item"
                :class="detailFlag ? 'collapse-title-active' : ''"
                @click.stop="handleDetailChoose"
              >
                询比价信息
              </div>
              <div
                class="collapse-title-item"
                :class="!detailFlag ? 'collapse-title-active' : ''"
                @click.stop="handleDetailChoose"
              >
                关联请购单信息
              </div>
            </div>
            <div
              v-if="
                pageType !== 'detail' && pageType !== 'check' && !contactAddShow
              "
              class="nofixed-search-button button-position"
            >
              <el-button class="btn add" @click.stop="handleContactOperate"
                ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
                >添加</el-button
              >
            </div>
            <div
              class="nofixed-search-button button-position"
              v-else
              v-if="pageType !== 'detail' && pageType !== 'check'"
            >
              <el-button
                class="btn add"
                @click.stop="handleContactAdd(contactFormRef)"
                ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
                >{{ operateTreeType == "edit" ? "保存" : "添加" }}</el-button
              >
              <el-button class="btn direction" @click.stop="handleRequestBack"
                ><el-icon class="icon" color="#fff"> <ArrowUp /> </el-icon
                >关闭</el-button
              >
            </div>
          </template>
          <div class="contact-info">
            <!-- 表格数据 -->
            <el-table
              v-show="detailFlag"
              :data="addInteriorTableData"
              border
              :height="
                pageType === 'detail' || pageType === 'check'
                  ? '100%'
                  : contactAddShow
                  ? '320px'
                  : '280px'
              "
              :header-cell-style="{ 'text-align': 'center' }"
            >
              <!-- 操作模式 -->
              <el-table-column
                label="操作"
                align="center"
                :show-overflow-tooltip="true"
                width="140px"
                v-if="pageType !== 'detail' && pageType !== 'check'"
              >
                <template #default="{ row, $index }">
                  <div class="table-operate">
                    <el-icon
                      v-if="row.preferred === 1"
                      title="设为首选"
                      color="#999999"
                      class="table-icon"
                      :size="20"
                      @click="handleOperate('preferred', row, $index)"
                    >
                      <Star />
                    </el-icon>
                    <el-icon
                      v-else
                      title="设为首选"
                      color="#007CEF"
                      class="table-icon"
                      :size="20"
                      @click="handleOperate('preferred', row, $index)"
                    >
                      <Star />
                    </el-icon>
                    <img
                      src="@/assets/icons/images/edit.png"
                      class="table-icon"
                      title="编辑"
                      @click="handleOperate('edit', row, $index)"
                    />
                    <img
                      src="@/assets/icons/images/delete.png"
                      class="table-icon"
                      title="删除"
                      @click="handleOperate('delete', row, $index)"
                    />
                  </div> </template
              ></el-table-column>
              <el-table-column
                label="物料编号"
                prop="materialCode"
                :show-overflow-tooltip="true"
                min-width="160"
              >
                <template #default="{ row }">
                  <span>{{ row.materialCode ? row.materialCode : "--" }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="物料名称"
                prop="materialName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="出厂型号"
                prop="factoryCode"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="技术参数"
                prop="technologyParameter"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="单位"
                prop="materialUnitName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="采购数量"
                prop="purchaseNumber"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="预算单价（元）"
                prop="budgetedPrice"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="预算总价（元）"
                :show-overflow-tooltip="true"
                min-width="160"
              >
                <template #default="{ row }">
                  {{ row.budgetedPrice * row.purchaseNumber }}
                </template>
              </el-table-column>
              <el-table-column
                label="询价单价（元）"
                prop="purchasePrice"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="税率（%）"
                prop="taxRate"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="税额（元）"
                prop="taxAmount"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="不含税金额（元）"
                prop="noTaxAmount"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="运费（元）"
                prop="freight"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="总金额（元）"
                :show-overflow-tooltip="true"
                min-width="160"
              >
                <template #default="{ row }">
                  {{ row.purchasePrice * row.purchaseNumber }}
                </template>
              </el-table-column>

              <el-table-column
                label="发票类型"
                prop="invoiceTypeName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="到货周期"
                prop="deliveryCycle"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="渠道"
                prop="channelName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="供应商"
                prop="supplierName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="生产厂商"
                prop="manufactureName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
            </el-table>
            <!-- 表格数据 -->
            <el-table
              ref="tableRef"
              v-show="!detailFlag"
              :data="RequestChooseList"
              border
              :height="'100%'"
              :header-cell-style="{ 'text-align': 'center' }"
              style="margin-bottom: 20px"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                type="selection"
                :selectable="checkSelect"
                width="55"
                align="center"
              />
              <el-table-column
                label="请购编号"
                prop="purchaseApplyCode"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="物料编号"
                prop="materialCode"
                :show-overflow-tooltip="true"
                min-width="160"
              >
                <template #default="{ row }">
                  <span>{{ row.materialCode ? row.materialCode : "--" }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="物料名称"
                prop="materialName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="出厂型号"
                prop="factoryCode"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="技术参数"
                prop="technologyParameter"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="单位"
                prop="materialUnitName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="请购数量"
                prop="purchaseNumber"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="单价（元）"
                prop="purchasePrice"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="总价（元）"
                :show-overflow-tooltip="true"
                min-width="160"
              >
                <template #default="{ row }">
                  {{ row.purchasePrice * row.purchaseNumber }}
                </template>
              </el-table-column>
              <el-table-column
                label="到货周期"
                prop="deliveryCycle"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="物料图片"
                :show-overflow-tooltip="true"
                min-width="200"
              >
                <template #default="{ row }">
                  <div class="image-content" v-if="row.suppFileInfoVos">
                    <!-- <template > -->
                    <el-image
                      v-for="(item, index) in row.suppFileInfoVos"
                      :key="index"
                      :preview-teleported="true"
                      style="width: 30px; height: 30px; margin-right: 5px"
                      :src="item.url"
                      :preview-src-list="showImg(item.url)"
                    >
                      <template #error>
                        <div class="image-slot">
                          <el-icon><icon-picture /></el-icon>
                        </div>
                      </template>
                    </el-image>
                    <!-- </template> -->
                  </div>
                  <span v-if="!row.suppFileInfoVos"> 暂无图片 </span>
                </template>
              </el-table-column>
              <el-table-column
                label="参考链接"
                prop="referenceLink"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="供应商"
                prop="supplierName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="生产厂商"
                prop="manufactureName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
            </el-table>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <SelectionMaterial
      v-if="selectionMaterialShow"
      v-model:selectionMaterialShow="selectionMaterialShow"
      @submitChoose="handleSelectMaterial"
    />
    <RequestDetail
      v-if="requestDetailShow"
      v-model:requestDetailShow="requestDetailShow"
      :RequestChooseList="RequestChooseList"
      @submitChoose="handleRequestDetail"
    />

    <el-dialog
      :title="title"
      v-model="auditDialogShow"
      width="600px"
      append-to-body
    >
      <el-form-item label="审核备注：" label-width="90">
        <el-input
          style="width: 100%"
          v-model="auditRemark"
          placeholder=""
          type="textarea"
          maxlength="2000"
          clearable
        />
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            style="color: #fff; background-color: rgba(67, 207, 124, 1)"
            v-if="auditResult == 3"
            @click="saveCheck()"
            v-loading="loadingCheck"
            >同意</el-button
          >
          <el-button
            style="color: #fff; background-color: rgba(245, 108, 108, 1)"
            v-if="auditResult == 4"
            @click="saveCheck()"
            v-loading="loadingCheck"
            >拒绝</el-button
          >
          <el-button
            style="color: #fff; background-color: rgba(245, 108, 108, 1)"
            v-if="auditResult == 6"
            @click="saveCheck()"
            v-loading="loadingCheck"
          >
            驳回</el-button
          >
          <el-button style="background-color: #fff" @click="closeAudit()"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Picture as IconPicture } from "@element-plus/icons-vue";
import SelectionMaterial from "./selectionMaterial";
import RequestDetail from "./requestDetail";
import Upload from "@/components/Upload/index";
import { checkRequestApi } from "@/api/purchase/request";
import { getUserListApi } from "@/api/information/customer";
import { getProjectListApi } from "@/api/sales/project";
import {
  addInquiryApi,
  editInquiryApi,
  getInquiryDetailApi,
  checkInquiryApi,
} from "@/api/purchase/inquiry";
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
import { getSupplierListApi } from "@/api/information/supplier";
import { nextTick } from "vue";
const { proxy } = getCurrentInstance();
const route = useRoute();
const emit = defineEmits([
  // 客户新增组件显隐
  "requestAddShow",
  // 更新客户新增组件显隐
  "update:requestAddShow",
  // 刷新父组件表格数据
  "refreshList",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
});

// 折叠栏默认展开
const activeNames = ref(["1", "2", "3", "4", "5"]);
// 客户表单引用
const requestFormRef = ref();
// 联系人表单引用
const contactFormRef = ref();
// 联系人操作类型
const operateType = ref("");
// 树表格操作
const operateTreeType = ref("");
// 选择审核
const auditDialogShow = ref(false);
const loadingCheck = ref(false);

// 新增联系人表单显隐
const contactAddShow = ref(false);
// 选择物料显隐
const selectionMaterialShow = ref(false);
// 选择请购明细显隐
const requestDetailShow = ref(false);
// 详情加载效果
const detailInfoShow = ref(false);
// 输入框引用
const refInput = ref();
// 下拉框引用
const refSelect = ref();
// 联系人当前索引(编辑使用)
const tableIndex = ref(null);
// 树表格当前索引(编辑使用)
const tableTreeIndex = ref(null);
// 采购类型列表
const typeList = ref([]);
// 渠道列表
const channelList = ref([]);
// 单位列表
const unitList = ref([]);
// 供应商列表
const suppliereList = ref([]);
// 项目列表
const projectList = ref([]);
// 请购单明细表格选中
const RequestChooseList = ref([]);
// 询比价信息、关联请购单信息显隐
const detailFlag = ref(true);
// 表格选择
const multipleSelection = ref([]);
// 新增内部表格数据
const addInteriorTableData = ref([]);
// 关联请购单信息明细
const tableRef = ref(null);
// 询比价信息明细表格数据
const purchaseDetailTable = ref([]);
// 序号列表
const indexList = ref([]);
// 拆分后关联请购单
const requestListSplit = ref([]);
// 默认税率列表
const taxRateList = ref([]);

// 客户表单数据模板
const requestFormTemplate = {
  applicantDate: "", // 申请日期
  applicantId: null, // 申请人id
  checkStatus: null, // 采购审核状态
  inquiryPriceId: 0, //	询比价id
  type: 0, // 按钮类型0：存为草稿；1；提交
  purchaseInqMaterialDetailLitsRespVos: [], // 请购单物料信息
  purchaseInquiryMaterialRespVos: [], // 询比价信息对象
};
// 询比价表单数据模板
const contactFormTemplate = {
  batchNumber: null, // 批次号
  preferred: 1, // 是否首选(0:是,1:否)
  budgetedPrice: null, // 预算单价
  channel: null, // 渠道
  channelName: null, // 渠道名称
  invoiceType: null, // 发票类型erp_invoice_type(0:专票,1:普票,2:替票)
  invoiceTypeName: null, // 发票类型erp_invoice_type(0:专票,1:普票,2:替票)
  freight: null, // 运费
  inquiryPriceId: null, //	询比价的id信息
  purchaseMaterialId: null,
  deliveryCycle: "", // 到货周期
  factoryCode: "", // 出厂编号
  manufactureName: "", // 生产厂商名称
  manufacturerId: null, // 生产厂商(也是供应商id)
  materialCode: "", // 	物料编号
  materialName: "", // 	物料名称
  materialUnit: null, // 	物料单位
  purchaseNumber: null, // 请购数量
  purchasePrice: null, // 	请购单价
  remarks: "", // 备注
  supplierId: null, // 供应商id
  supplierName: "", // 供应商名称
  technologyParameter: "", // 技术参数
  purchaseInqMaterialDetailLitsRespVos: [], // 请购单物料信息
  budgeteAllPrice: null, // 预算总价
  allPrice: null, // 总价
  taxRate: null, // 税率
  taxAmount: null, // 税额
  noTaxAmount: null, // 不含税金额
};
const data = reactive({
  // 客户表单
  requestForm: JSON.parse(JSON.stringify(requestFormTemplate)),
  // 联系人表单
  contactForm: JSON.parse(JSON.stringify(contactFormTemplate)),
  // 客户表单校验规则
  queryRules: {
    applicantDate: [
      { required: true, message: "请选择申请日期", trigger: "change" },
    ],
    applicantId: [
      { required: true, message: "请选择申请人", trigger: "change" },
    ],
    applicantType: [
      { required: true, message: "请选择采购类型", trigger: "change" },
    ],
    deliveryDate: [
      { required: true, message: "请选择期望交付日期", trigger: "change" },
    ],
    projectId: [
      { required: true, message: "请选择项目名称", trigger: "change" },
    ],
    workOrderId: [
      { required: true, message: "请选择运维工单", trigger: "change" },
    ],
    cloudServer: [
      { required: true, message: "请选择是否为云服务器", trigger: "change" },
    ],
    budgetAmount: [
      { required: true, message: "请输入预算金额", trigger: "blur" },
    ],
    applicantReason: [
      { required: true, message: "请输入申请事由", trigger: "blur" },
    ],
    remarks: [{ required: true, message: "请输入采购说明", trigger: "blur" }],
  },
  // 联系人表单校验规则
  queryContactRules: {
    materialName: [
      { required: true, message: "请输入物料名称", trigger: "blur" },
    ],
    factoryCode: [
      { required: true, message: "请输入出厂型号", trigger: "blur" },
    ],
    technologyParameter: [
      { required: true, message: "请输入技术参数", trigger: "blur" },
    ],
    materialUnit: [
      { required: true, message: "请选择单位", trigger: "change" },
    ],
    purchaseNumber: [
      { required: true, message: "请输入采购数量", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value > 999999 || value < 1) {
            callback(new Error("采购数量为1到999999之间的数字"));
          } else {
            if (value.toString().split(".")[1]?.length > 2) {
              callback(new Error("采购数量小数点后最多两位"));
            } else {
              callback();
            }
          }
        },
      },
    ],
    budgetedPrice: [
      { required: true, message: "请输入预算单价", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value > 999999 || value < 0) {
            callback(new Error("预算单价为0到999999之间的数字"));
          } else {
            if (value.toString().split(".")[1]?.length > 2) {
              callback(new Error("预算单价小数点后最多两位"));
            } else {
              callback();
            }
          }
        },
      },
    ],
    purchasePrice: [
      { required: true, message: "请输入询价单价", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value > 999999 || value < 1) {
            callback(new Error("询价单价为1到999999之间的数字"));
          } else {
            if (value.toString().split(".")[1]?.length > 2) {
              callback(new Error("询价单价小数点后最多两位"));
            } else {
              callback();
            }
          }
        },
      },
    ],
    taxRate: [
      { required: true, message: "请输入税率", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value > 100 || value < 0) {
            callback(new Error("税率为0到100之间的数字"));
          } else {
            callback();
          }
        },
      },
    ],
    freight: [
      { required: true, message: "请输入运费", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value > 999999 || value < 0) {
            callback(new Error("运费为0到999999之间的数字"));
          } else {
            if (value.toString().split(".")[1]?.length > 2) {
              callback(new Error("运费小数点后最多两位"));
            } else {
              callback();
            }
          }
        },
      },
    ],
    invoiceType: [
      { required: true, message: "请选择发票类型", trigger: "change" },
    ],
    deliveryCycle: [
      { required: true, message: "请输入到货周期", trigger: "blur" },
    ],
    channel: [{ required: true, message: "请选择渠道", trigger: "change" }],
  },
  // 角色列表
  contactTypeList: [],
  // 所属行业列表
  industryList: [],
  // 用户列表
  userList: [],
  auditRemark: "",
  auditResult: "",
  applyId: "",
});

const {
  requestForm,
  contactForm,
  queryRules,
  queryContactRules,
  contactTypeList,
  industryList,
  userList,
  auditRemark,
  auditResult,
  applyId,
} = toRefs(data);

const handleCheckBtn2 = (requestFormRef, type, title) => {
  auditRemark.value = "";
  if (type == 3) {
    auditRemark.value = "同意";
  }

  auditResult.value = type;
  (applyId.value = requestForm.value.inquiryPriceId),
    (auditDialogShow.value = true);
  loadingCheck.value = false;
};

const saveCheck = async () => {
  if (auditRemark.value === null || auditRemark.value === "") {
    ElMessage.error("审核备注不能为空");
    return;
  }

  const obj = {
    checkStatus: auditResult.value,
    inquiryPriceId: applyId.value,
    auditRemark: auditRemark.value,
  };
  try {
    loadingCheck.value = true;
    const res = await checkInquiryApi(obj);
    auditDialogShow.value = false;

    //loadingCheck.value =false;

    if (res.code === 200) {
      ElMessage.success(res.msg);
    } else {
      ElMessage.error(res.msg);
      return;
    }
    loadingCheck.value = false;
    emit("update:requestAddShow", false);
    emit("refreshList", false);
  } catch (error) {
    loadingCheck.value = false;
    emit("update:requestAddShow", false);
    emit("refreshList", false);
    // ElMessage.error(error);
  }
};

const closeAudit = () => {
  auditRemark.value = "";
  auditResult.value = "";
  applyId.value = "";
  auditDialogShow.value = false;
};

function flattenData(data) {
  let flattenedData = [];

  function flattenChildren(children, parentId) {
    for (let child of children) {
      let flattenedChild = { ...child };
      flattenedChild.parentId = parentId;
      flattenedData.push(flattenedChild);

      if (child.children) {
        flattenChildren(child.children, child.batchNumber);
      }
    }
  }

  for (let item of data) {
    flattenedData.push({ ...item });
    if (item.children) {
      flattenChildren(item.children, item.batchNumber);
    }
  }

  return flattenedData;
}

/**
 * @description: 保存
 * @param {Object} requestFormRef 客户表单引用
 */
const handleAddSave = async (requestFormRef, type) => {
  let flattenedData = flattenData(
    JSON.parse(JSON.stringify(purchaseDetailTable.value))
  );
  flattenedData.forEach((item) => {
    item.children = [];
  });
  // requestForm.value
  // purchaseInquiryMaterialRespVos
  if (!requestFormRef) return;
  if (
    (props.pageType == "add" || props.pageType == "edit") &&
    RequestChooseList.value.length == 0
  ) {
    ElMessage.warning("请添加关联请购单！");
    return;
  }

  if (
    (props.pageType == "add" || props.pageType == "edit") &&
    purchaseDetailTable.value.length == 0
  ) {
    ElMessage.warning("请制作询比价单！");
    return;
  }
  if (props.pageType == "add" || props.pageType == "edit") {
    let flag = false;
    RequestChooseList.value.forEach((item) => {
      if (!item.checked) {
        flag = true;
      }
    });
    if (flag == true) {
      return ElMessage.warning("存在未制作询比价的请购单，请删除后再提交！");
    }
  }
  await requestFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          requestForm.value.type = type;
          let res;
          if (!requestForm.value.inquiryPriceId) {
            // 新增询比价
            res = await addInquiryApi({
              ...requestForm.value,
              purchaseInquiryMaterialRespVos: flattenedData,
              purchaseInqMaterialDetailLitsRespVos: RequestChooseList.value,
            });
          } else {
            // 编辑询比价
            res = await editInquiryApi({
              ...requestForm.value,
              purchaseInquiryMaterialRespVos: flattenedData,
              purchaseInqMaterialDetailLitsRespVos: RequestChooseList.value,
            });
          }
          if (res.code === 200) {
            emit("update:requestAddShow", false);
            emit("refreshList", false);
            ElMessage.success(res.msg);
            requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    }
  });
};

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail" || props.pageType === "check") {
    emit("updateFollowAddShow", false);
    emit("update:requestAddShow", false);
    requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:requestAddShow", false);
        requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
      })
      .catch(() => {});
  }
};

/**
 * @description: 处理手动输入
 */
const handleHand = () => {
  contactForm.value = JSON.parse(JSON.stringify(contactFormTemplate));
  contactFormRef.value.resetFields();
};

/**
 * @description: 处理选择物料
 */
const handleMaterial = () => {
  selectionMaterialShow.value = true;
};

/**
 * @description: 处理选择请购单
 */
const handleRequestChoose = () => {
  requestDetailShow.value = true;
};

/**
 * @description: 处理物料选择
 */
const handleSelectMaterial = (value) => {
  if (value) {
    selectionMaterialShow.value = false;
    contactForm.value.materialCode = value.materialCode;
    contactForm.value.materialName = value.materialName;
    contactForm.value.factoryCode = value.factoryCode;
    contactForm.value.technologyParameter = value.technologyParameter;
    contactForm.value.materialUnit = value.materialUnit;
    contactForm.value.materialUnitName = value.materialUnitName;
    contactForm.value.supplierName = value.distributorName;
    contactForm.value.supplierId = value.supplierId;
    contactForm.value.manufacturerId = value.manufacturerId;
    contactForm.value.manufactureName = value.manufactureName;
  } else {
    ElMessage.info("请选择物料");
  }
};

/**
 * @description: 处理请购明细选择
 */
const handleRequestDetail = (value) => {
  if (value.length) {
    requestDetailShow.value = false;
    value.forEach((item) => {
      RequestChooseList.value.push(item);
    });
  } else {
    ElMessage.info("请选择请购单");
  }
};

/**
 * @description: 处理供应商、生产厂家选择
 */
// const handleSuppliereSelect = (value) => {};

// const querySearch = (queryString, cb) => {
//   const results = queryString
//     ? suppliereList.value.filter(createFilter(queryString))
//     : suppliereList.value;
//   cb(results);
// };
// const createFilter = (queryString) => {
//   return (restaurant) => {
//     return (
//       restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
//     );
//   };
// };

/**
 * @description: 处理询比价明细选择
 * @param {Number} type 类型
 */
const handleDetailChoose = (type) => {
  detailFlag.value = !detailFlag.value;
};

/**
 * @description: 处理人员选择
 * @param {Number} value 选择值
 */
const handleUserChange = (value) => {
  if (value) {
    const selectUser = userList.value.find((item) => item.userId === value);
    if (selectUser) {
      requestForm.value.deptName = selectUser.dept.deptName;
    }
  } else {
    requestForm.value.deptName = "";
  }
};

/**
 * @description: 处理单位选择
 * @param {Number} value 选择值
 */
const handleUnitChange = (value) => {
  contactForm.value.materialUnitName =
    unitList.value.find((item) => item.value === value)?.label || "";
};

/**
 * @description: 处理渠道选择
 * @param {Number} value 选择值
 */
const handleChannelChange = (value) => {
  contactForm.value.channelName =
    channelList.value.find((item) => item.value === value)?.label || "";
};

/**
 * @description: 处理发票类型选择
 * @param {Number} value 选择值
 */
const handleTypeChange = (value) => {
  contactForm.value.invoiceTypeName =
    typeList.value.find((item) => item.value === value)?.label || "";
};

/**
 * @description: 表格选择禁用
 * @param row：当前行数据
 * @param index：当前第几位
 */
const checkSelect = (row, index) => {
  let isChecked = true;
  if (row.checked) {
    // 判断里面是否存在某个参数
    isChecked = false;
  } else {
    isChecked = true;
  }
  return isChecked;
};

/**
 * @description: 预览照片
 * @param {String} img 图片地址
 */
const showImg = (img) => {
  let imgArr = [];
  imgArr.push(img);
  return imgArr;
};

/**
 * @description: 计算总价
 * @param {Number} value 选择值
 */
const handlePrice = () => {
  // 预算： 单价*数量
  if (contactForm.value.budgetedPrice && contactForm.value.purchaseNumber) {
    contactForm.value.budgeteAllPrice = (
      contactForm.value.budgetedPrice * contactForm.value.purchaseNumber
    ).toFixed(2);
  }
  // 总金额： 单价*数量+运费
  if (contactForm.value.purchasePrice && contactForm.value.purchaseNumber) {
    let freight = contactForm.value.freight
      ? Number(contactForm.value.freight)
      : 0;
    contactForm.value.allPrice = (
      contactForm.value.purchasePrice * contactForm.value.purchaseNumber +
      freight
    ).toFixed(2);
  }
  // 税额： 单价 / (1+税率) * 税率
  if (contactForm.value.purchasePrice && contactForm.value.taxRate) {
    contactForm.value.taxAmount = (
      (contactForm.value.purchasePrice /
        (1 + contactForm.value.taxRate * 0.01)) *
      contactForm.value.taxRate *
      0.01
    ).toFixed(2);
  }

  // 不含税金额： 单价 / (1+税率) * 税率
  if (contactForm.value.purchasePrice && contactForm.value.taxAmount) {
    contactForm.value.noTaxAmount = (
      contactForm.value.purchasePrice - contactForm.value.taxAmount
    ).toFixed(2);
  }
};

/**
 * @description: 新增、编辑联系人
 * @param {Object} contactFormRef 联系人表单引用
 */
const handleContactAdd = async (contactFormRef) => {
  if (!contactFormRef) return;
  await contactFormRef.validate(async (valid) => {
    if (valid) {
      if (operateType.value === "edit") {
        addInteriorTableData.value[tableIndex.value] = {
          ...JSON.parse(JSON.stringify(contactForm.value)),
          batchNumber: new Date().getTime(),
        };
      } else {
        addInteriorTableData.value.push({
          ...JSON.parse(JSON.stringify(contactForm.value)),
          batchNumber: new Date().getTime(),
        });
      }
      contactForm.value = JSON.parse(JSON.stringify(contactFormTemplate));
      contactFormRef.resetFields();
      nextTick(() => {
        refInput.value.focus();
        if (operateType.value == "edit") {
          contactAddShow.value = false;
        }
      });
    } else {
      console.log("error submit!");
    }
  });
};

/**
 * @description: 处理联系人操作
 */
const handleContactOperate = () => {
  if (RequestChooseList.value && RequestChooseList.value.length) {
    const hasTrueElement = RequestChooseList.value.some(
      (item) => !item.checked
    );
    if (!hasTrueElement) {
      return ElMessage.info("表格中请购单已被关联，请选择请购单");
    }
    contactAddShow.value = true;
    operateTreeType.value = "add";
    nextTick(() => {
      refInput.value.focus();
    });
  } else {
    ElMessage.info("请选择关联请购单");
  }
};
/**
 * @description: 指定行颜色
 */
const tableRowClassName = ({ row, rowIndex }) => {
  if (row.checked == true) {
    return "warm-row";
  }
};

/**
 * @description: 关闭
 */
const handleRequestBack = () => {
  if (addInteriorTableData.value.length == 1) {
    addInteriorTableData.value[0].preferred = 0;
  }
  if (addInteriorTableData.value.length) {
    const hasPreferredZero = addInteriorTableData.value.some(
      (item) => item.preferred === 0
    );
    if (!hasPreferredZero) {
      return ElMessage.info("请设置询比价首选");
    }
    if (!multipleSelection.value.length) {
      return ElMessage.info("请关联请购单");
    }
    // 关联选择的请购单
    addInteriorTableData.value.forEach((item) => {
      item.purchaseInqMaterialDetailLitsRespVos = multipleSelection.value;
    });
    // 询比价明细表格数据
    const originalArray = addInteriorTableData.value;
    let endArr = {};
    originalArray.forEach((item) => {
      if (item.preferred === 0) {
        item.children = [];
        endArr = item;
        originalArray.forEach((value) => {
          if (value.preferred === 1) {
            endArr.children.push({ ...value, parentId: item.batchNumber });
          }
        });
      }
    });
    // 编辑
    if (operateTreeType.value === "edit") {
      purchaseDetailTable.value[tableTreeIndex.value] = endArr;
    } else {
      // 新增
      purchaseDetailTable.value.push(endArr);
    }
    // 关联请购单选中处理
    RequestChooseList.value.forEach((item) => {
      multipleSelection.value.forEach((value) => {
        if (item.purchaseMaterialId == value.purchaseMaterialId) {
          item.checked = true;
        }
      });
    });
    addInteriorTableData.value = [];
    multipleSelection.value = [];
    contactAddShow.value = false;
    // nextTick(() => {
    //   refSelect.value.focus();
    // });
  } else {
    contactAddShow.value = false;
  }
  detailFlag.value = true;
};

/**
 * @description: 处理合计
 */
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 1) {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    // 只对amount这一列进行总计核算。
    if (
      column.property === "purchaseNumber" ||
      column.property === "budgetedPrice" ||
      column.property === "purchasePrice" ||
      // column.property === "taxRate" ||
      column.property === "taxAmount" ||
      column.property === "freight" ||
      column.property === "noTaxAmount" ||
      column.property === "allPrice" ||
      column.property === "budgeteAllPrice"
    ) {
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
        if (column.property !== "purchaseNumber") {
          sums[index] = sums[index].toFixed(2); // 保留2位小数，解决小数列合计精度缺失的问题
        }
        // sums[index] += "元";
      } else {
        sums[index] = "";
      }
    }
  });
  // if (props.pageType === "add" || props.pageType === "edit") {
  //   // sums[16] = sums[11] * sums[8] + sums[15];
  //   // sums[10] = sums[9] * sums[8];
  //   // sums[15] = null;
  //   // 14总价 9单价 6数量
  //   sums[15] = sums[10] * sums[7] + sums[14];
  //   sums[9] = sums[8] * sums[7];
  //   sums[14] = null;
  // } else {
  //   // 14总价 9单价 6数量
  //   sums[15] = sums[10] * sums[7] + sums[14];
  //   sums[9] = sums[8] * sums[7];
  //   sums[14] = null;
  // }
  return sums;
};

/**
 * @description: 处理询比价信息明细树表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleTreeOperate = (type, row, tabIndex) => {
  switch (type) {
    case "edit":
      // 删除同时清除关联请购单勾选状态
      let treeData = {};
      if (RequestChooseList.value && RequestChooseList.value.length > 0) {
        RequestChooseList.value.forEach((item) => {
          if (
            purchaseDetailTable.value &&
            purchaseDetailTable.value.length > 0
          ) {
            purchaseDetailTable.value.forEach((purItem, index) => {
              if (purItem.batchNumber === row.batchNumber) {
                tableTreeIndex.value = index;
                treeData = row;
              }
            });
          }
        });
      }

      let newData = [];
      if (treeData.children) {
        treeData.children.forEach((chiItem) => {
          chiItem.parentId = "";
          newData.push(chiItem);
        });
      }
      newData.unshift(treeData);
      newData[0].children = [];
      addInteriorTableData.value = newData;

      // 选中关联请购单勾选状态
      if (RequestChooseList.value && RequestChooseList.value.length > 0) {
        RequestChooseList.value.forEach((item) => {
          newData[0].purchaseInqMaterialDetailLitsRespVos.forEach((value) => {
            if (item.purchaseMaterialId == value.purchaseMaterialId) {
              item.checked = false;
            }
          });
        });
      }
      contactAddShow.value = true;
      setTimeout(() => {
        // 回显关联请购单选中状态
        if (RequestChooseList.value && RequestChooseList.value.length > 0) {
          RequestChooseList.value.forEach((item, index) => {
            newData[0].purchaseInqMaterialDetailLitsRespVos.forEach(
              (newItem) => {
                if (item.purchaseMaterialId == newItem.purchaseMaterialId) {
                  tableRef.value.toggleRowSelection(item);
                }
              }
            );
          });
        }
      }, 500);
      operateTreeType.value = "edit";
      break;
    case "delete":
      // 删除同时清除关联请购单勾选状态
      if (RequestChooseList.value && RequestChooseList.value.length > 0) {
        RequestChooseList.value.forEach((item) => {
          purchaseDetailTable.value.forEach((purItem, index) => {
            if (purItem.batchNumber === row.batchNumber) {
              purItem.purchaseInqMaterialDetailLitsRespVos.forEach((value) => {
                if (item.purchaseMaterialId == value.purchaseMaterialId) {
                  item.checked = false;
                }
              });
              // 延时删除等待循环
              setTimeout(() => {
                purchaseDetailTable.value.splice(index, 1);
              }, 100);
            }
          });
        });
      }

      break;
    default:
      break;
  }
};
/**
 * @description: 处理联系人表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleOperate = (type, row, tabIndex) => {
  switch (type) {
    case "edit":
      tableIndex.value = tabIndex;
      contactForm.value = {
        ...JSON.parse(JSON.stringify(row)),
        suppFileInfoVos: JSON.parse(JSON.stringify(row)).suppFileInfoVos
          ? JSON.parse(JSON.stringify(row)).suppFileInfoVos
          : [],
      };
      contactForm.value.allPrice = (
        contactForm.value.purchasePrice * contactForm.value.purchaseNumber
      ).toFixed(2);
      contactAddShow.value = true;
      operateType.value = "edit";
      nextTick(() => {
        refInput.value.focus(); // 聚焦
      });
      break;
    case "preferred":
      addInteriorTableData.value.forEach((item, index) => {
        if (tabIndex === index) {
          item.preferred = 0;
        } else {
          item.preferred = 1;
        }
      });
      break;

    default:
      addInteriorTableData.value.splice(tabIndex, 1);
      break;
  }
};

/**
 * @description: 处理表格选中
 */
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

/**
 * @description: 处理关联请购单表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleRequestOperate = (type, row, tabIndex) => {
  if (row.checked) {
    return ElMessage.info("该请购单已关联，请先解除关联");
  }
  RequestChooseList.value.splice(tabIndex, 1);
};

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (id) => {
  try {
    detailInfoShow.value = true;
    const res = await getInquiryDetailApi(id);
    if (res) {
      requestForm.value = {
        ...res.purchaseInquiryInfoRespVo,
      };
      // 关联请购
      RequestChooseList.value = res.purchaseInqMaterialDetailLitsRespVos;
      // 询比价列表
      purchaseDetailTable.value = proxy.handleTree(
        res.inqMaterialDetailLitsRespVos,
        "batchNumber"
      );
      // 处理关联请购单勾选
      purchaseDetailTable.value.map((item, index) => getIndex(item, index));
      purchaseDetailTable.value.forEach((item) => {
        item.allPrice = (
          item.purchasePrice * item.purchaseNumber +
          (item.freight ? item.freight : 0)
        ).toFixed(2);
        item.budgeteAllPrice = (
          item.budgetedPrice * item.purchaseNumber
        ).toFixed(2);
        item.purchaseInqMaterialDetailLitsRespVos.forEach((chiItem) => {
          RequestChooseList.value.forEach((reqItem) => {
            if (chiItem.purchaseMaterialId == reqItem.purchaseMaterialId) {
              reqItem.checked = true;
            }
          });
        });
      });

      // 查看详情关联请购单排序 例：1、1
      purchaseDetailTable.value.forEach((item, itemIndex) => {
        item.purchaseInqMaterialDetailLitsRespVos.forEach(
          (chiItem, chiItemIndex) => {
            requestListSplit.value.push({
              ...chiItem,
              index: itemIndex + 1,
              childrenIndex: chiItemIndex + 1,
            });
          }
        );
      });
      detailInfoShow.value = false;
    }
  } catch (error) {
    detailInfoShow.value = false;
  }
};

/**
 * @description: 处理请购明细选择
 * @param {Number} id
 */
const handleRequestDetailChoose = (val) => {
  RequestChooseList.value = val;
};

const getIndex = (data, index) => {
  indexList.value.push(index + 1);
  if (data.children) {
    data.children.map((item, index) => getIndex(item, index));
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  // 类型列表
  await getDictsApi("erp_invoice_type").then((res) => {
    if (res.code === 200) {
      typeList.value = res.data;
    }
  });

  // 渠道列表
  await getDictsApi("erp_channel").then((res) => {
    if (res.code === 200) {
      channelList.value = res.data;
    }
  });

  // 单位列表
  await getDictsApi("material_unit").then((res) => {
    if (res.code === 200) {
      unitList.value = res.data;
    }
  });

  // 供应商列表
  await getSupplierListApi().then((res) => {
    if (res.code === 200) {
      res.rows.forEach((item) => {
        item.value = item.supplierName;
      });
      suppliereList.value = res.rows;
    }
  });

  // 项目列表
  await getProjectListApi({}, {}).then((res) => {
    if (res.code === 200) {
      projectList.value = res.rows;
    }
  });

  await getUserListApi({}).then((res) => {
    // if (res.code === 200) {
    //   userList.value = res.rows;
    // }
    if (res.length > 0) {
      userList.value = res;
    }
  });

  // 税率列表
  await getDictsApi("default_tax_rate").then((res) => {
    if (res.code === 200) {
      taxRateList.value = res.data;
    }
  });

  // // 销售部门列表
  // await getDeptListApi().then((res) => {
  //   if (res.code === 200) {
  //     deptList.value = res.data;
  //     nextTick(() => {
  //       refSelect.value.focus(); // 聚焦
  //     });
  //   }
  // });
}

onMounted(() => {
  getDicts();
  if (props.pageType === "add") {
    nextTick(() => {
      refSelect.value && refSelect.value.focus();
    });
  }
});

defineExpose({
  handleDetailInfo,
  handleRequestDetailChoose,
});
</script>

<style lang="scss">
.warm-row {
  background-color: #f0f0f0 !important;
}
</style>
<style lang="scss" scoped>
.requestAdd {
  padding: 20px 20px;
  width: 100%;
  height: 100%;
  .request-info {
    padding: 20px 20px 5px 20px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }
  .contact-info {
    padding-top: 20px;
  }

  :deep(.el-table) {
    th.el-table__cell {
      background: #f8f8f8 !important;
    }
  }
  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 268px !important;
    height: 34px !important;
  }
  .search-input {
    width: 268px;
    height: 34px;
  }
  .image-content {
    width: 100%;
    line-height: 0px;
    overflow: auto;
    height: 30px;
  }
  .collapse-title {
    font-weight: bold;
    font-size: 16px;
    color: #303133 !important;
    display: flex;
  }
  .collapse-title-item {
    height: 100%;
    margin-right: 20px;
    &:hover {
      color: #007cef !important;
    }
  }
  .collapse-title-active {
    color: #007cef !important;
  }
}
.auto-top {
  width: 100%;
  position: absolute;
  top: 0px;
  display: flex;
  font-weight: bold;
}
.auto-item {
  width: 125px;
  text-align: left;
  white-space: nowrap; /* 禁止换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 使用省略号表示超出部分 */
}
.el-autocomplete .el-autocomplete-suggestion {
  max-height: 200px; /* 设置最大高度 */
  overflow-y: auto; /* 超出高度时显示滚动条 */
}
:deep(.el-form-item--default) {
  margin-bottom: 22px;
}
:deep(.el-form-item--default .el-form-item__error) {
  padding-top: 5px;
}
</style>
